/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.web.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.web.entity.WxAgents;
import com.jeeplus.modules.web.entity.WxAgentsEquipment;
import com.jeeplus.modules.web.entity.YjEquipment;
import com.jeeplus.modules.web.mapper.WxAgentsEquipmentMapper;
import com.jeeplus.modules.web.mapper.WxAgentsMapper;
import com.jeeplus.modules.web.service.WxAgentsEquipmentService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 代理商绑定设备Controller
 *
 * @author rongjie
 * @version 2017-08-06
 */
@Controller
@RequestMapping(value = "${adminPath}/web/wxAgentsEquipment")
public class WxAgentsEquipmentController extends BaseController {

	@Autowired
	private WxAgentsEquipmentService wxAgentsEquipmentService;
	@Autowired
	private WxAgentsEquipmentMapper wxAgentsEquipmentMapper;
	@Autowired
	private WxAgentsMapper wxAgentsMapper;

	@ModelAttribute
	public WxAgentsEquipment get(@RequestParam(required = false) String id) {
		WxAgentsEquipment entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = wxAgentsEquipmentService.get(id);
		}
		if (entity == null) {
			entity = new WxAgentsEquipment();
		}
		return entity;
	}

	/**
	 * 获取某个代理商的绑定设备
	 *
	 * @return
	 */
	@RequiresPermissions("web:wxAgentsEquipment:list")
	@RequestMapping(value = "equipments")
	public List<WxAgentsEquipment> findWxAgentsEquipmentByAgentID(@RequestParam(required = true) Integer agentId) {
		return wxAgentsEquipmentService.getAgentEquipments(agentId);
	}

	/**
	 * 代理商绑定设备列表页面
	 */
	@RequiresPermissions("web:wxAgentsEquipment:list")
	@RequestMapping(value = { "list", "" })
	public String list() {
		return "modules/web/wxAgentsEquipmentList";
	}

	/**
	 * 代理商绑定设备列表数据
	 */
	@ResponseBody
	@RequiresPermissions("web:wxAgentsEquipment:list")
	@RequestMapping(value = "data")

	public Map<String, Object> data(WxAgentsEquipment wxAgentsEquipment, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		WxAgents wxAgents = new WxAgents();
		wxAgents.setUserName(currentUser.getMobile());
		if (!currentUser.getId().equals("1")) {
			if(wxAgentsEquipment.getAgents()!=null && wxAgentsEquipment.getAgents().getUserName()!=null){
				wxAgents.setUserName(wxAgentsEquipment.getAgents().getUserName());
			}
			WxAgents temp = wxAgentsMapper.findUniqueByProperty("username", currentUser.getMobile());
			wxAgents.setId(temp.getId());
			wxAgentsEquipment.setAgents(wxAgents);

		}
		Page<WxAgentsEquipment> page = wxAgentsEquipmentService.findPage(new Page<WxAgentsEquipment>(request, response),
				wxAgentsEquipment);

		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑代理商绑定设备表单页面
	 */
	@RequiresPermissions(value = { "web:wxAgentsEquipment:view", "web:wxAgentsEquipment:add",
			"web:wxAgentsEquipment:edit" }, logical = Logical.OR)
	@RequestMapping(value = "form")
	public String form(WxAgentsEquipment wxAgentsEquipment, Model model) {
		model.addAttribute("wxAgentsEquipment", wxAgentsEquipment);
		if (StringUtils.isBlank(wxAgentsEquipment.getId())) {// 如果ID是空为添加
			model.addAttribute("isAdd", true);
		}
		return "modules/web/wxAgentsEquipmentForm";
	}

	/**
	 * 保存代理商绑定设备
	 */
	@RequiresPermissions(value = { "web:wxAgentsEquipment:add", "web:wxAgentsEquipment:edit" }, logical = Logical.OR)
	@RequestMapping(value = "save")
	public String save(WxAgentsEquipment wxAgentsEquipment, Model model, RedirectAttributes redirectAttributes)
			throws Exception {
		if (!beanValidator(model, wxAgentsEquipment)) {
			return form(wxAgentsEquipment, model);
		}
		//TODO 一台设备不能绑定于多个代理商
		// 新增或编辑表单保存
		String[] agentIds = StringUtils.split(wxAgentsEquipment.getAgents().getId(), ",");
		// 传入多个代理商时，不允许绑定
		if (null != agentIds && agentIds.length > 1) {
			model.addAttribute("message", "只能为单个代理商绑定一台或多台设备");
			return form(wxAgentsEquipment, model);
		}
		String[] equipmentIds = StringUtils.split(wxAgentsEquipment.getEquipment().getId(), ",");
		List<WxAgentsEquipment> agentEquipments = wxAgentsEquipmentService.getAgentEquipments(Integer.parseInt(wxAgentsEquipment.getAgents().getId()));
		List<YjEquipment> equipmentList = agentEquipments.stream().map(WxAgentsEquipment::getEquipment).collect(Collectors.toList());

		if (null != equipmentIds) {
			// 允许一次为一个代理商绑定多台设备
			if (equipmentIds.length > 1) {
				List<WxAgentsEquipment> wxAgentsEquipmentList = new ArrayList<WxAgentsEquipment>();
				// 生成批量录入的数据
				for (String equimentId : equipmentIds) {
					if(!equipmentList.contains(equimentId)){
						WxAgentsEquipment temp = new WxAgentsEquipment();
						// WxAgentsEquipment默认构造器未初始化agent和equiment实例
						temp.setAgents(new WxAgents());
						temp.setEquipment(new YjEquipment());

						temp.setRemarks(wxAgentsEquipment.getRemarks());
						temp.getEquipment().setId(equimentId);
						temp.getAgents().setId(wxAgentsEquipment.getAgents().getId());
						// temp.setDelFlag("0");
						wxAgentsEquipmentList.add(temp);
					}else{
						model.addAttribute("message", "重复绑定，id:"+equimentId);
						return form(wxAgentsEquipment, model);
					}
				}
				if(wxAgentsEquipmentList.size() > 0){
					wxAgentsEquipmentService.batchAddAgentsEquipment(wxAgentsEquipmentList);
				}
			} else {
				wxAgentsEquipmentService.save(wxAgentsEquipment);// 保存
			}
		} else {
			model.addAttribute("message", "未选择需要绑定的设备");
			return form(wxAgentsEquipment, model);
		}
		addMessage(redirectAttributes, "保存代理商绑定设备成功");
		return "redirect:" + Global.getAdminPath() + "/web/wxAgentsEquipment/?repage";
	}

	/**
	 * 删除代理商绑定设备
	 */
	@ResponseBody
	@RequiresPermissions("web:wxAgentsEquipment:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(WxAgentsEquipment wxAgentsEquipment, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		wxAgentsEquipmentService.delete(wxAgentsEquipment);
		j.setMsg("删除代理商绑定设备成功");
		return j;
	}

	/**
	 * 批量删除代理商绑定设备
	 */
	@ResponseBody
	@RequiresPermissions("web:wxAgentsEquipment:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] = ids.split(",");
		for (String id : idArray) {
			wxAgentsEquipmentService.delete(wxAgentsEquipmentService.get(id));
		}
		j.setMsg("删除代理商绑定设备成功");
		return j;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("web:wxAgentsEquipment:export")
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public AjaxJson exportFile(WxAgentsEquipment wxAgentsEquipment, HttpServletRequest request,
			HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "代理商绑定设备" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Page<WxAgentsEquipment> page = wxAgentsEquipmentService
					.findPage(new Page<WxAgentsEquipment>(request, response, -1), wxAgentsEquipment);
			new ExportExcel("代理商绑定设备", WxAgentsEquipment.class).setDataList(page.getList()).write(response, fileName)
					.dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出代理商绑定设备记录失败！失败信息：" + e.getMessage());
		}
		return j;
	}

	/**
	 * 导入Excel数据
	 *
	 */
	@RequiresPermissions("web:wxAgentsEquipment:import")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WxAgentsEquipment> list = ei.getDataList(WxAgentsEquipment.class);
			for (WxAgentsEquipment wxAgentsEquipment : list) {
				try {
					wxAgentsEquipmentService.save(wxAgentsEquipment);
					successNum++;
				} catch (ConstraintViolationException ex) {
					failureNum++;
				} catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条代理商绑定设备记录。");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条代理商绑定设备记录" + failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入代理商绑定设备失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/web/wxAgentsEquipment/?repage";
	}

	/**
	 * 下载导入代理商绑定设备数据模板
	 */
	@RequiresPermissions("web:wxAgentsEquipment:import")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "代理商绑定设备数据导入模板.xlsx";
			List<WxAgentsEquipment> list = Lists.newArrayList();
			new ExportExcel("代理商绑定设备数据", WxAgentsEquipment.class, 1).setDataList(list).write(response, fileName)
					.dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/web/wxAgentsEquipment/?repage";
	}

}